package com.xingyun.wangyiyun;

import androidx.appcompat.app.AppCompatActivity;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class MainActivity extends AppCompatActivity {
    private MediaPlayer mPlayer = new MediaPlayer();
    private EditText mSearch;
    private ListView list_one;
    private LinearLayout head_search;
    private LinearLayout head_play;
    private LinearLayout body_search;
    private LinearLayout body_play;
    private TextView text_search;
    private TextView text_play;
    private MyAdapter mAdapter = null;
    private RoundImageView songPic = null;
    private List<Data> mData = null;
    private ListView song_list;
    private ListView comment_list;
    private SongAdapter songAdapter = null;
    private List<Song> mSong = null;
    private CommentAdapter commentAdapter = null;
    private List<Comment> mComment = null;
    private TextView mLyric;
    private int[] timeList;
    private String[] strList;
    private Handler TimerHandler=null;
    private Runnable myTimerRun=null;
    private int lyricIndex = 0;
    private TextView songName;
    private TextView iconPlay;
    private TextView iconPause;

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        text_search = findViewById(R.id.text_search);
        text_play = findViewById(R.id.text_play);
        iconPause = findViewById(R.id.iconPause);
        iconPlay = findViewById(R.id.iconPlay);
        TextView searchIcon = findViewById(R.id.searchIcon);
        searchIcon.setTypeface(iconfont);
        iconPlay.setTypeface(iconfont);
        iconPause.setTypeface(iconfont);
        text_search.setTypeface(iconfont);
        text_play.setTypeface(iconfont);
        mLyric = findViewById(R.id.lyric);
        songName = findViewById(R.id.songName);
        list_one = (ListView) findViewById(R.id.list_one);
        mData = new LinkedList<Data>();
        mAdapter = new MyAdapter((LinkedList<Data>) mData,MainActivity.this);
        mAdapter.add(new Data(R.drawable.c0h,"邓紫棋"));
        list_one.setAdapter(mAdapter);
        song_list = (ListView) findViewById(R.id.song_list);
        comment_list = (ListView) findViewById(R.id.comment_list);
        mSong = new LinkedList<Song>();
        songAdapter = new SongAdapter((LinkedList<Song>) mSong,MainActivity.this);
        mComment = new LinkedList<Comment>();
        commentAdapter = new CommentAdapter((LinkedList<Comment>) mComment,MainActivity.this);
        list_one.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @SuppressLint("WrongConstant")
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Data item = mData.get(i);
                System.out.println(item.getContent());
                getSearch(item.getContent());
                list_one.setVisibility(8);
                song_list.setVisibility(0);
                mSearch.clearFocus();
            }
        });
        songPic = findViewById(R.id.song_pic);
        final ObjectAnimator mAnimator = ObjectAnimator.ofFloat(songPic, "rotation", 0.0f, 360.0f);
        mAnimator.setDuration(36000);
        mAnimator.setRepeatCount(Animation.INFINITE);
        mAnimator.setInterpolator(new LinearInterpolator());
        songPic.setOnClickListener(new View.OnClickListener(){
            @SuppressLint("WrongConstant")
            @Override
            public void onClick(View view) {
                if(mPlayer.isPlaying()){
                    mPlayer.pause();
                    mAnimator.pause();
                    iconPlay.setVisibility(8);
                    iconPause.setVisibility(0);
                }else{
                    mPlayer.start();
                    mAnimator.resume();
                    iconPause.setVisibility(8);
                    iconPlay.setVisibility(0);
                }
                System.out.println(mPlayer.getCurrentPosition());
            }
        });
        head_search = findViewById(R.id.head_search);
        head_play = findViewById(R.id.head_play);
        body_search = findViewById(R.id.body_search);
        body_play = findViewById(R.id.body_play);
        head_search.setOnClickListener(new View.OnClickListener(){
            @SuppressLint("WrongConstant")
            @Override
            public void onClick(View view) {
                body_play.setVisibility(8);
                body_search.setVisibility(0);
                text_play.setBackgroundResource(0);
                text_search.setBackgroundResource(R.drawable.border_red);
            }
        });
        head_play.setOnClickListener(new View.OnClickListener(){
            @SuppressLint("WrongConstant")
            @Override
            public void onClick(View view) {
                body_search.setVisibility(8);
                body_play.setVisibility(0);
                text_search.setBackgroundResource(0);
                text_play.setBackgroundResource(R.drawable.border_red);
            }
        });
        Glide.with(this).load("http://p4.music.126.net/fkqFqMaEt0CzxYS-0NpCog==/18587244069235039.jpg").into(songPic);
        song_list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @SuppressLint("WrongConstant")
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Song item = mSong.get(i);
                System.out.println(item.getId());
                playSong(item.getId());
                lyricIndex = 0;
                Glide.with(MainActivity.this).load(item.getImgUrl()).into(songPic);
                mAnimator.start();
                body_search.setVisibility(8);
                body_play.setVisibility(0);
                text_search.setBackgroundResource(0);
                text_play.setBackgroundResource(R.drawable.border_red);
                songName.setText(item.getContent()+" - "+item.getSingerName().split("-")[0]);
            }
        });
        mSearch = findViewById(R.id.search);
        mSearch.setOnFocusChangeListener(new View.OnFocusChangeListener(){
            @SuppressLint("WrongConstant")
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if(hasFocus){
                    song_list.setVisibility(8);
                    list_one.setVisibility(0);
                }else{
                    InputMethodManager manager = ((InputMethodManager)MainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE));
                    if (manager != null){
                        manager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                System.out.println(hasFocus);
            }
        });
        mSearch.addTextChangedListener(new TextWatcher(){
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().equals("")){
                    mData.clear();
                    list_one.setAdapter(mAdapter);
                    return;
                }
                getSuggest(s.toString());
                Log.e("TextWatcher","输入之后，一般就用这个！！！"+s.toString());
            }
        });
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                lyricIndex = 0;
            }
        });
    }
    public void playSong(final Integer title){
        new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    String data = getParams("{\"ids\":\"["+title+"]\",\"level\":\"standard\",\"encodeType\":\"aac\"}");
                    JSONObject object = ajax("/weapi/song/enhance/player/url/v1",data);
                    JSONArray jsonArray = object.getJSONArray("data");
                    JSONObject ObjectInfo = jsonArray.getJSONObject(0);
                    final String url = ObjectInfo.optString("url");
                    if(TimerHandler!=null){
                        TimerHandler.removeCallbacks(myTimerRun);
                    }
                    getLyric(title);
                    getComment(title);
                    list_one.post(new Runnable() {
                        @Override
                        public void run() {
                            mPlayer.stop();
                            mPlayer.reset();
                            try {
                                mPlayer.setDataSource(url);
                                mPlayer.prepare();
                                mPlayer.start();
                                mPlayer.setLooping(true);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void getSearch(final String title){
        new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    String data = getParams("{\"s\":\""+title+"\",\"limit\":20,\"offset\":0,\"type\":1,\"strategy\":5,\"queryCorrect\":true}");
                    JSONObject object = ajax("/weapi/search/get",data);
                    JSONObject ObjectInfo = object.optJSONObject("result");
                    JSONArray jsonArray = null;
                    assert ObjectInfo != null;
                    jsonArray = ObjectInfo.getJSONArray("songs");
                    final JSONArray finalJsonArray = jsonArray;
                    list_one.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mSong.clear();
                                for (int i = 0; i < finalJsonArray.length(); i++){
                                    JSONObject object1 = finalJsonArray.getJSONObject(i);
                                    JSONArray ar = object1.getJSONArray("ar");
                                    JSONObject ObjectInfo1 = object1.optJSONObject("al");
                                    String singer_name = "";
                                    for(int j=0;j<ar.length();j++){
                                        JSONObject temp = ar.getJSONObject(j);
                                        singer_name = singer_name + temp.optString("name") + " / ";
                                    }
                                    singer_name = singer_name.substring(0,singer_name.length()-2)+object1.optString("name");
                                    songAdapter.add(new Song(object1.optInt("id"),object1.optString("name"),ObjectInfo1.optString("picUrl"),singer_name));
                                }
                                song_list.setAdapter(songAdapter);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void getComment(final Integer id){
        new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    String data = getParams("{\"resourceType\":4,\"resourceId\":"+id+",\"limit\":15,\"commentsNum\":5}");
                    JSONObject object = ajax("/weapi/v1/resource/comments/get",data);
                    JSONArray jsonArray = object.getJSONArray("hotComments");
                    final JSONArray finalJsonArray = jsonArray;
                    list_one.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mComment.clear();
                                for (int i = 0; i < finalJsonArray.length(); i++){
                                    JSONObject object1 = finalJsonArray.getJSONObject(i);
                                    JSONObject ObjectInfo1 = object1.optJSONObject("user");
                                    commentAdapter.add(new Comment(object1.optInt("commentId"),object1.optString("content"),ObjectInfo1.optString("avatarUrl")));
                                }
                                comment_list.setAdapter(commentAdapter);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void getLyric(final int id){
        new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    String data = getParams("{\"id\":"+id+",\"lv\":0,\"tv\":0}");
                    JSONObject object = ajax("/weapi/song/lyric",data);
                    JSONObject ObjectInfo = object.optJSONObject("lrc");
                    String lyric = ObjectInfo.optString("lyric");
                    String[] newStr = lyric.split("\n");
                    String[] newList = new String[100];
                    int index = 0;
                    for(int i=0;i<newStr.length;i++){
                        if(!newStr[i].endsWith("]")){
                            newList[index] = newStr[i];
                            index++;
                        }
                    }
                    System.out.println(newList.length);
                    timeList = new int[index+1];
                    timeList[index] = 99999999;
                    strList = new String[index];
                    for(int i=0;i<index;i++){
                        newStr = newList[i].split("]");
                        String time = newStr[0];
                        int m = Integer.parseInt(time.substring(2,3));
                        int s = Integer.parseInt(time.substring(4,6));
                        timeList[i]=(m*60+s)*1000;
                        strList[i]=newStr[1];
                    }
                    mLyric.post(new Runnable() {
                        @Override
                        public void run() {
                            mLyric.setText(strList[0]);
                            TimerHandler=new Handler();
                            myTimerRun=new Runnable(){
                                @Override
                                public void run() {
                                    if(mPlayer.getCurrentPosition()>timeList[lyricIndex]){
                                        mLyric.setText(strList[lyricIndex]);
                                        lyricIndex++;
                                    }
                                    TimerHandler.postDelayed(this, 1000);
                                }
                            };
                            TimerHandler.postDelayed(myTimerRun,0);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public String getParams(String str) throws Exception {
        str = encrypt(str,"0CoJUm6Qyw8W8jud");
        str = encrypt(str,"t7syWlaSI2aQzqln");
        str = Uri.encode(str);
        return "params="+str+"&encSecKey=4458e1e36cee979266565e87368ba3b34a8adc168d486cab051f585f605e6a9f674b70267dddf1c13eb7a677d5eb44cd8122fe87435f96d4f2deda993207dc69ca9794e0511df60a7a092c3d49aac76f7a6cadf680aa7976a91c8fba5d1e7b7a7f390476c183991aa8d45b9ba60af8485f71423f1bbcdbde36d780877f27195f";
    }
    public void getSuggest(final String val){
        new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    JSONObject object = ajax("/weapi/search/suggest/keyword",getParams("{\"s\":\""+val+"\"}"));
                    JSONObject ObjectInfo = object.optJSONObject("result");
                    JSONArray jsonArray = null;
                    assert ObjectInfo != null;
                    jsonArray = ObjectInfo.getJSONArray("allMatch");
                    final JSONArray finalJsonArray = jsonArray;
                    list_one.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mData.clear();
                                for (int i = 0; i < finalJsonArray.length(); i++){
                                    JSONObject object1 = finalJsonArray.getJSONObject(i);
                                    System.out.println(object1.optString("keyword"));
                                    mAdapter.add(new Data(R.drawable.c0h,object1.optString("keyword")));
                                }
                                list_one.setAdapter(mAdapter);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public JSONObject ajax(String path, String params) throws JSONException {
        HttpURLConnection conn = null;
        try {
            URL url = new URL("https://music.163.com"+ path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            byte[] requestBody = null;
            requestBody = new String(params).getBytes("UTF-8");
            os.write(requestBody);
            os.flush();
            os.close();
            InputStream is = conn.getInputStream();
            byte[] result = null;
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer))!=-1) {
                    baos.write(buffer,0,len);
                }
                is.close();
                baos.close();
                result = baos.toByteArray();
                String res = new String(result);
                return new JSONObject(res);

            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            assert conn != null;
            conn.disconnect();
        }
        return new JSONObject("");
    }
    public static String encrypt(String content,String keyStr) throws Exception {
        String str = keyStr;
        byte[] secretKeyEncoded = str.getBytes("UTF-8");
        // 创建AES秘钥
        SecretKeySpec key = new SecretKeySpec(secretKeyEncoded, "AES");
        // 创建密码器
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        // 初始化加密器
        str = "0102030405060708";
        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(str.getBytes("UTF-8")));
        // 加密
        byte[] res = cipher.doFinal(content.getBytes("UTF-8"));
        return Base64.encodeToString(res,Base64.DEFAULT);
    }
}